<template>
  <view class="page">
    <view class="body" v-if="dataInfo && dataInfo.id">
      <view class="head" id="head">
        <video
          class="video"
          :src="dataInfo.file_url"
          v-if="dataInfo.type == '2'"
          object-fit="cover"
        ></video>
        <template v-else-if="dataInfo.type == '3'">
          <view
            :style="{ backgroundImage: `url(${dataInfo.cover_img_url})` }"
            class="thumb"
          ></view>
          <audio-player :src="dataInfo.file_url"></audio-player>
        </template>
        <view
          :style="{ backgroundImage: `url(${dataInfo.cover_img_url})` }"
          class="thumb"
          v-else
        ></view>
        <view class="title">
          {{ dataInfo.title }}
        </view>

        <view class="desc">
          <view class="tag">{{ dataInfo.typeText }}</view>
          {{ dataInfo.read_num }}人{{ unit }}过
        </view>
        <view class="append-title">
          <view class="bd">课程章节</view>
          <view class="ft">
            <image
              :src="imgBaseUrlV2 + 'arrow_down.png'"
              class="arrow"
              :class="{ active: showFixed }"
              @click="onShowFixed"
            />
          </view>
        </view>
        <view class="append" id="append" :class="{ isFixed }">
          <view class="scroll-view-box">
            <scroll-view
              :scroll-x="true"
              class="scroll-view"
              :scroll-into-view="intoView"
            >
              <view
                class="item"
                v-for="(item, index) in dataList"
                :class="{ active: index === current }"
                :key="item.id"
                :id="item.id"
                @click="onChange(index)"
              >
                {{ item.title }}
              </view>
            </scroll-view>
          </view>
        </view>
      </view>

      <view class="content">
        <template> </template>
        <view class="title">课程介绍</view>

        <view class="text">
          <rich-text :nodes="dataInfo.content"></rich-text>
        </view>
      </view>
    </view>

    <view
      class="fixed"
      v-show="showFixed"
      :class="{ active: showFixed }"
      @click="onClickFixed"
    >
      <view class="fixed-body" @click.stop="onClickFixedBody">
        <image
          :src="imgBaseUrlV2 + 'delete2.png'"
          class="close"
          @click="onHideFixed"
        ></image>

        <scroll-view
          class="scroll-view"
          :scroll-x="true"
          :scroll-into-view="intoView"
        >
          <view
            class="item"
            v-for="(item, index) in dataList"
            :key="item.id"
            :class="{ active: index === current }"
            @click="onChange(index)"
          >
            <image :src="item.icon" mode="" v-if="item.icon" class="icon" />
            <view class="name">
              {{ item.title }}
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <Message ref="message"></Message>
  </view>
</template>

<script>
import { delayFunc } from "@/common/util";
import viewModule from "@/common/mixins/view-module";
import { mapState } from "vuex";
import { imgBaseUrl, imgBaseUrlV2 } from "@/common/config";
import { getCollegeTag } from "@/common/api/college";
import qs from "qs";
import { throttle, debounce } from "@/utils";
import audioPlayer from "@/components/public/item/audio";
import {
  getCollegeCourseArticleDetail,
  addCourseArticleReadNumber,
  addCourseReadNumber,
} from "@/common/api/college";

export default {
  mixins: [viewModule],
  components: {
    audioPlayer,
  },
  computed: {
    ...mapState("User", ["userInfo"]),
    unit() {
      if (this.dataInfo && this.dataInfo.type == "audio") {
        return "听";
      }
      return "看";
    },
  },
  data() {
    return {
      imgBaseUrl,
      imgBaseUrlV2,
      dataList: [],
      dataInfo: {},
      current: -1,
      icons: [
        {
          label: 1,
          value: imgBaseUrlV2 + "xueyuan_tu_h.png",
        },
        {
          label: 2,
          value: imgBaseUrlV2 + "xueyuan_shipin_h.png",
        },
        {
          label: 3,
          value: imgBaseUrlV2 + "xueyuan_yinpin_h.png",
        },
      ],
      showFixed: false,
      isFixed: false,
      headHeight: 0,
      mixinViewOptions: {
        getURL: "/getCollegeCourseArticleList",
        isPage: true,
        isShowLoading: true,
        reachBottom: false,
        createdIsNeed: false,
        pullDown: true,
      },
      intoView: "",
      dataForm: {},
    };
  },
  methods: {
    fetchComplete(err, data = [], res = {}) {
      addCourseReadNumber({
        id: this.dataForm.course_id,
      });
      if (err) {
        this.message.error(res.message || "获取数据失败!");
      }
      let item;
      let list = data.map((i) => {
        item = this.icons.find((it) => it.label == i.type);
        i.icon = item ? item.value : "";
        return {
          ...i,
          id: "key" + i.id + "",
          oldId: i.id,
          content: i.content || "",
          typeText: this.$getDictLabel("repositoryArticleType", i.type),
        };
      });
      this.$nextTick(() => {
        let index = list.findIndex((i) => i.oldId == this.articleId);
        this.onChange(index === -1 ? 0 : index);
      });
      return list;
    },
    initData() {
      return Promise.all([this.getDataList()]);
    },
    onShowFixed() {
      this.showFixed = true;
    },
    onHideFixed() {
      this.showFixed = false;
    },
    onClickFixed() {
      this.showFixed = false;
    },
    onClickFixedBody() {},

    onChange(index) {
      let current = this.current;
      this.dataInfo = this.dataList[index];
      this.current = index;
      this.intoView = this.dataInfo.id + "";
      console.log(this.intoView, "?   this.intoView");
      if (this.dataInfo.title) {
        uni.setNavigationBarTitle({
          title: this.dataInfo.title,
        });
      }
      if (this.dataInfo && !this.dataInfo.content) {
        addCourseArticleReadNumber({
          id: this.dataInfo.oldId,
        });
        getCollegeCourseArticleDetail({
          id: this.dataInfo.oldId,
        })
          .then((res) => {
            let data = res.data || {};
            let content = data.content || "";
            let match = content.match(
              /<[img]+\s+(.*?)(?<id>\w*?)[\s'"](.*?)>/g
            );
            if (match) {
              match.forEach((item, idx) => {
                let len = item.length;
                let matchStyle = item.match(/[style=]+[\s'"]/);
                if (matchStyle) {
                }
                let _str =
                  item.slice(0, len - 2) + ' style="max-width:100%;"/>';
                content = content.replace(item, _str);
              });
            }

            this.dataInfo.content = content;
          })
          .catch((err) => {});
      }
      this.$nextTick(() => {
        this.initFixed();
        this.onHideFixed();
      });
    },
    initFixed() {
      const query = uni.createSelectorQuery().in(this);
      if (!this.query) {
        this.query = query;
      }
      query
        .select("#head")
        .boundingClientRect((data) => {
          if (!data) return;
          let { height } = data;
          this.headHeight = height;
          console.log(this.headHeight, "?  this.headHeight");
        })
        .exec();
    },
  },
  onLoad(q) {
    // this.onChange(3);
    // this.initData();
    console.log(q, "?q");
    this.articleId = q.id;
    if (q.course_id) {
      this.dataForm.course_id = this.course_id = q.course_id;
      this.initData();
    }
    if (q.title) {
      uni.setNavigationBarTitle({
        title: q.title,
      });
    }
    setTimeout(() => {
      this.initFixed();
    }, 300);
  },
  onPageScroll: debounce(function (e) {
    let { scrollTop } = e;
    this.isFixed = this.headHeight && scrollTop > this.headHeight - 87;
    console.log(this.headHeight, ":", scrollTop);
  }, 100),
};
</script>

<style lang="stylus" scoped>
@import '~@/common/stylus/variable';
@import '~@/common/stylus/mixins';

.page {
  min-height: calc(100vh - var(--window-top));
  background: linear-gradient(180deg, #0D1523 0%, #102945 100%);
  overflow: auto;
}

.body {
  padding-bottom: 20rpx;

  >.head {
    >.video {
      display: block;
      height: 360rpx;
      width: 100%;
    }

    >.thumb {
      display: block;
      height: 360rpx;
      background-size: cover;
      background-position: center center;
    }

    >.title {
      font-size: 36rpx;
      line-height: 52rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: bold;
      color: color-white;
      padding: 20rpx 24rpx;
    }

    >.desc {
      display: flex;
      padding: 0 24rpx;
      line-height: 40rpx;
      color: color-white;
      font-size: 28rspx;

      >.tag {
        display: inline-block;
        height: 40rpx;
        line-height: 40rpx;
        font-size: 24rpx;
        background: #F7BD3C;
        border-radius: 4rpx;
        color: #fff;
        padding: 0 8rpx;
        margin-right: 20rpx;
      }
    }

    >.append-title {
      display: flex;
      padding: 0 24rpx;
      font-size: 32rpx;
      line-height: 1;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: bold;
      color: color-white;
      padding-top: 24rpx;

      >.bd {
        flex: 1;
      }

      >.ft {
        flex: 0 0 auto;

        >.arrow {
          display: block;
          width: 40rpx;
          height: 40rpx;
          transition: all 0.3s;
          transform: rotate(-90deg);

          &.active {
            transform: rotate(0);
          }
        }
      }
    }

    >.append {
      z-index: 3;
      white-space: nowrap;
      flex-wrap: nowrap;
      padding-bottom: 30rpx;
      padding-top: 24rpx;
      border-bottom: 10rpx solid #EEEEEE;

      &.isFixed {
        position: fixed;
        width: 100%;
        left: 0;
        top: var(--window-top);
        background: #fff;
      }

      >.scroll-view-box {
        padding: 0 20rpx;

        >.scroll-view {
          white-space: nowrap;
          height: 72rpx;

          .item {
            display: inline-block;
            height: 72rpx;
            line-height: 72rpx;
            font-size: 28rpx;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: bold;
            color: color-white;
            border: 1rpx solid #C9CACA;
            transition: all 0.3s;
            padding: 0 18rpx;
            border-radius: 10rpx;
            min-width: 240rpx;
            text-align: center;
            margin-right: 10rpx;

            &:first-child {
              margin-left: 0;
            }

            &:last-child {
              margin-right: 24rpx;
            }

            &.active {
              color: #fff;
              border-color: transparent;
              background: #3f7dff;
            }
          }
        }
      }
    }
  }

  >.content {
    padding: 0 24rpx;

    >.title {
      font-size: 32rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: bold;
      color: color-white;
      line-height: 1;
      padding: 23rpx 0 23rpx;
    }

    >.text {
      font-size: 28rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: color-white;
      line-height: 42rpx;
    }
  }
}

.scroll-view {
}

.fixed {
  position: fixed;
  width: 100vw;
  height: calc(100vh - var(--window-top));
  left: 0;
  top: var(--window-top);
  background: rgba(0, 0, 0, 0.3);

  &.active {
    >.fixed-body {
      transform: translate3d(0, 0, 0);
    }
  }

  >.fixed-body {
    position: absolute;
    width: 100%;
    height: 610rpx;
    bottom: 0;
    left: 0;
    transition: all 0.3s;
    background: #fff;
    transform: translate3d(0, 100%, 0);
    // padding-bottom: 2rpx;
    padding: 94rpx 0 0 0;

    >.scroll-view {
      height: 516rpx;

      .item {
        position: relative;
        display: flex;
        font-size: 32rpx;
        line-height: 48rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #333333;
        // padding-left: 24rpx;
        margin-bottom: 12rpx;
        padding: 0 40rpx;
        min-height: 72rpx;
        align-items: center;

        &.active {
          background: rgba(63, 125, 255, 0.08);
        }

        .icon {
          width: 40rpx;
          height: 40rpx;
          margin-right: 20rpx;
        }

        .name {
          no-wrap();
        }

        &:after {
          position: absolute;
          content: '';
          left: 0;
          top: 0;
          width: 4rpx;
          height: 100%;
          background: #3f7dff;
          transform: scale(0);
          transition: all 0.3s;
        }

        &.active {
          &:after {
            transform: scale(1);
          }
        }
      }
    }

    >.close {
      position: absolute;
      display: block;
      top: 26rpx;
      right: 26rpx;
      width: 40rpx;
      height: 40rpx;
    }
  }
}
</style>
